'use server';

import { cache } from 'react';
import { gfetch } from '@/utils/back/fetch';

const fetchServerSideProducts = cache(async (params: any) => {
  // const authHeader = headers().get('authorization')
  const querys = new URLSearchParams(params);

  const res = await gfetch<Obj>(`/v2/products?${querys.toString()}`);

  if (res.data?.result instanceof Array) {
    const initDatas = res.data.result.map((sku: any) => ({ ...sku }));
    console.log('🔎 ✔️ ===> Products >', initDatas?.length);
    return { ...res, result: initDatas };
  } else {
    return null;
  }
});

export const getServerSideProducts = async (params: any) => {
  const startTime = new Date().getTime();
  const res = await fetchServerSideProducts(params);
  console.log(
    '🔎 Products time:',
    ((new Date().getTime() - startTime) / 1000).toFixed(3)
  );
  return res;
};

export async function getProductDetailSvc(sku: string) {
  const res = await gfetch(`/v2/products/${sku}`);

  return res;
}
